package com.tx.java8.fork_join;

import java.util.concurrent.RecursiveTask;

/**
 *
 */
public class ForkJoinCalc extends RecursiveTask<Long> {
    private long start;
    private long end;

    //临界值，设为一万，即小任务中包含一万个数
    private static final long THRESHOLD = 10000L;

    public ForkJoinCalc(long start, long end) {
        this.start = start;
        this.end = end;
    }

    //执行的方法
    @Override
    protected Long compute() {
        long length = end - start;
        long sum = 0;
        if(length <= THRESHOLD){ //如果长度小于临界值
            for (long i=0 ;i<=end; i++) {
                sum += i;
            }
            return sum;
        }else{
            long middle = (start + end) / 2;
            //拆分成子任务
            ForkJoinCalc left = new ForkJoinCalc(start,middle);
            //把任务压到线程中
            left.fork();

            ForkJoinCalc right = new ForkJoinCalc(middle+1,end);
            //把任务压到线程中
            right.fork();

            //把计算结果合起来
            return left.join() + right.join();
        }
    }
}